/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rest.jbpm.task;
import org.jbpm.api.cmd.Command;
import org.jbpm.api.cmd.Environment;
import org.jbpm.api.task.Task;
import org.hibernate.*;
import org.hibernate.criterion.Restrictions;
import org.jbpm.pvm.internal.task.TaskImpl;

/**
 *
 * @author jump
 */
public class FindTaskById implements Command<Task> {
    
    private final String id;
    
    public FindTaskById(String id) {
        this.id = id;
    }

    @Override
    public Task execute(Environment environment) throws Exception {
        
        Session session = null;
        SessionFactory sessionFactory = environment.get(SessionFactory.class);
        try {

            session = sessionFactory.openSession();
            Task task = (Task) session.createCriteria(TaskImpl.class, "task")
                    .add(Restrictions.eq("id",Long.parseLong(id)))
                    .setFetchMode("execution", FetchMode.JOIN)
                    .setFetchMode("execution.variables", FetchMode.JOIN)
                    .setFetchMode("execution.activity", FetchMode.JOIN)
                    .setFetchMode("execution.activity.outgoingTransitions", FetchMode.JOIN)
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
                    .setFirstResult(0).uniqueResult();
            
            return task;
            
        } finally {
            if(session != null) session.close();
        }
    }
    
}
